package com.trackerapp.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.trackerapp.model.CellIDLocation;
import com.trackerapp.model.DatabaseModel;
import com.trackerapp.model.PushMessage;


public class CellIDCacheManager {
    private static final String TAG = CellIDCacheManager.class.getSimpleName();
    private SQLiteDatabase database;
    private DatabaseHandler dbHelper;
    private static CellIDCacheManager instance;
    private static Context mContext;

	private CellIDCacheManager() {
		dbHelper = new DatabaseHandler(mContext);
		open();
	}
	
	public static void initialiseContext(Context context) {
		CellIDCacheManager.mContext = context;
    }
	
	public static CellIDCacheManager getInstance() {
		if(instance == null) {
			instance = new CellIDCacheManager();
		}
		return instance;
	}

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        if (dbHelper != null)
            dbHelper.close();
    }


    public long addCellId(CellIDLocation location) {
        ContentValues values = new ContentValues();
        values.put(DatabaseModel.CELLID.CURRENT_CELL_ID, location.getCurrentCellId());
        values.put(DatabaseModel.CELLID.PREV_CELL_ID, location.getPreviousCellId());
        values.put(DatabaseModel.CELLID.LATITUDE, location.getLatitude());
        values.put(DatabaseModel.CELLID.LONGITUDE, location.getLongitude());
        values.put(DatabaseModel.CELLID.ACCURACY, location.getAccuracy());
        long insertId = 0;
        try {
            insertId = database.insertOrThrow(DatabaseModel.CELL_ID_TABLE, null, values);
        } catch (SQLiteConstraintException ex) {
            insertId = -100;
            Log.v(TAG, "Skipped creation for cell ID cache as it's already existed");
        } catch (SQLException ex) {
            insertId = -101;
            Log.v(TAG, "Skipped creation for cell ID cache as it's already existed");
        }
        return insertId;
    }

    public CellIDLocation getCellIDLocation(int currentCellId, int previousCellId) {
        CellIDLocation location = null;
        String where = DatabaseModel.CELLID.CURRENT_CELL_ID + "=?" + " AND " + DatabaseModel.CELLID.PREV_CELL_ID + "=?";
        String args[] = {Integer.toString(currentCellId), Integer.toString(previousCellId)};

        Cursor cursor = database.query(DatabaseModel.CELL_ID_TABLE,
                null, where, args, null, null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    location = new CellIDLocation();
                    location.setId(cursor.getLong(cursor.getColumnIndex(DatabaseModel.CELLID.CELLID_ID)));
                    location.setCurrentCellId(currentCellId);
                    location.setPreviousCellId(previousCellId);
                    location.setLatitude(cursor.getFloat(cursor.getColumnIndex(DatabaseModel.CELLID.LATITUDE)));
                    location.setLongitude(cursor.getFloat(cursor.getColumnIndex(DatabaseModel.CELLID.LONGITUDE)));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        
        return location;
    }

    public void updateCellIDLocation(CellIDLocation location) {
        ContentValues values = new ContentValues();
        values.put(DatabaseModel.CELLID.CURRENT_CELL_ID, location.getCurrentCellId());
        values.put(DatabaseModel.CELLID.PREV_CELL_ID, location.getPreviousCellId());
        values.put(DatabaseModel.CELLID.LATITUDE, location.getLatitude());
        values.put(DatabaseModel.CELLID.LONGITUDE, location.getLongitude());
        values.put(DatabaseModel.CELLID.ACCURACY, location.getAccuracy());

        String where = DatabaseModel.CELLID.CURRENT_CELL_ID + "=?" + " AND " + DatabaseModel.CELLID.PREV_CELL_ID + "=?";
        String args[] = {Integer.toString(location.getCurrentCellId()), Integer.toString(location.getPreviousCellId())};
        int rowsaffected = database.updateWithOnConflict(DatabaseModel.CELL_ID_TABLE, values, where, args, SQLiteDatabase.CONFLICT_REPLACE);

        if (rowsaffected == 0) {
            //Add to table.
            addCellId(location);
        }
    }
    
    public long addPushMessage(PushMessage pushMessage) {
        ContentValues values = new ContentValues();
        values.put(DatabaseModel.PUSH_NOTIFICATION.MESSAGE, pushMessage.getPush_message());
        values.put(DatabaseModel.PUSH_NOTIFICATION.PUSH_MESSAGE_ID, pushMessage.getPush_messag_id());
        values.put(DatabaseModel.PUSH_NOTIFICATION.SENDER, pushMessage.getSender());
        values.put(DatabaseModel.PUSH_NOTIFICATION.CREATED_AT, System.currentTimeMillis()/1000);
        long insertId = 0;
        try {
            insertId = database.insertOrThrow(DatabaseModel.PUSH_NOTIFICATION_TABLE, null, values);
        } catch (SQLiteConstraintException ex) {
            insertId = -100;
            Log.v(TAG, "Skipped creation for cell ID cache as it's already existed");
        } catch (SQLException ex) {
            insertId = -101;
            Log.v(TAG, "Skipped creation for cell ID cache as it's already existed");
        }
        return insertId;    	
    }
    
    public List<PushMessage> getAllPushMessages() {
    	
    	List<PushMessage> messages = new ArrayList<PushMessage>();    	
    	
		Cursor cursor = database.query(DatabaseModel.PUSH_NOTIFICATION_TABLE,
				null,null, null, null, null, DatabaseModel.PUSH_NOTIFICATION.PUSH_MESSAGE_ID+","+DatabaseModel.PUSH_NOTIFICATION.CREATED_AT);
		
		if (cursor != null ) {
            if  (cursor.moveToFirst()) {
                  do {
                	  PushMessage message = new PushMessage();
                	  message.setId(cursor.getLong(cursor.getColumnIndex(DatabaseModel.PUSH_NOTIFICATION.PUSH_ID)));
                	  message.setPush_message(cursor.getString(cursor.getColumnIndex(DatabaseModel.PUSH_NOTIFICATION.MESSAGE)));
                	  message.setPush_messag_id(cursor.getString(cursor.getColumnIndex(DatabaseModel.PUSH_NOTIFICATION.PUSH_MESSAGE_ID)));
                	  message.setSender(cursor.getString(cursor.getColumnIndex(DatabaseModel.PUSH_NOTIFICATION.SENDER)));
                	  message.setCreatedAt(cursor.getLong(cursor.getColumnIndex(DatabaseModel.PUSH_NOTIFICATION.CREATED_AT)));
                	  messages.add(message);
                  }while (cursor.moveToNext());
            } 
       }
	   
	   if(cursor != null) 
			cursor.close();

       return messages;
    }
    
    public void deletePushMessage(PushMessage id) {
    	
    }
}
